package taller.integrationLayer.listener;

import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import taller.businessLayer.BusinessFacade;
import taller.excepcion.ParserException;
import taller.xml.parser.FacturaParser;
import taller.xml.parser.XStreamParser;

import com.thoughtworks.xstream.XStream;


@MessageDriven(
		activationConfig = { 
				@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue"),
				@ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/recibirFacturaQueue")
		})
public class ReceptorDeFacturas implements MessageListener {
	@EJB
	private BusinessFacade businessFacade;
	
    public ReceptorDeFacturas() {
    }
	
    public void onMessage(Message message) {
    	if (message instanceof TextMessage) {
    		try{
    			TextMessage textMessage = (TextMessage) message;
    			
	    		XStreamParser parser = new XStreamParser();
	    		XStream xs = parser.obtenerXStream();
	    		xs.alias("Factura", FacturaParser.class); 
	    		xs.aliasField("Item", FacturaParser.class, "items");
	    		
	    		String xml = textMessage.getText();
	    		System.out.println("Factura recibida :");
	    		System.out.println(xml);
	    		
	    		FacturaParser facturaRecibida = (FacturaParser) xs.fromXML(xml);
	    		parser.liberarXStream();
	    		
	    		businessFacade.guardarFactura(facturaRecibida.getFacturaVO());
	    		
	    		System.out.println("Factura persistida en la DB");
    		} catch (ParserException e) {
				e.printStackTrace();
			} catch (JMSException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
    }

}
